package com.eqdd.yiqidian.ui.yiqixue.info

import android.graphics.Color
import android.os.Bundle
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.LinearLayoutManager
import android.text.Html
import android.text.Spannable
import android.text.SpannableString
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import com.eqdd.yiqidian.R
import com.eqdd.yiqidian.adapter.GridSpacingItemDecoration
import com.eqdd.yiqidian.adapter.recycleadapter.ItemClickSupport
import com.eqdd.yiqidian.adapter.slimadapter.SlimAdapterEx
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector
import com.eqdd.yiqidian.base.BaseActivity
import com.eqdd.yiqidian.base.Config
import com.eqdd.yiqidian.bean.rebuild.HttpResultRows
import com.eqdd.yiqidian.bean.rebuild.LearnVideoListBean
import com.eqdd.yiqidian.box.span.MovementMethod.ClickMovementMethod
import com.eqdd.yiqidian.box.span.TagSpan
import com.eqdd.yiqidian.http.DialogCallBack
import com.eqdd.yiqidian.http.HttpConfig
import com.eqdd.yiqidian.http.HttpResult
import com.eqdd.yiqidian.http.JsonCallBack
import com.eqdd.yiqidian.kotlin.imgPathPreview
import com.eqdd.yiqidian.kotlin.popMenu
import com.eqdd.yiqidian.ui.gongneng.renshi.train.TrainCourseMatchActivity
import com.eqdd.yiqidian.ui.yiqixue.LearnSearchActivity
import com.eqdd.yiqidian.utils.DateUtil
import com.eqdd.yiqidian.utils.PreferenceUtil
import com.eqdd.yiqidian.utils.ScrollLoadMoreUtil
import com.example.library.AutoFlowLayout
import com.example.library.FlowAdapter
import com.lzy.okgo.OkGo
import com.lzy.okgo.model.Response
import kotlinx.android.synthetic.main.activity_lecture_info.*
import kotlinx.android.synthetic.main.activity_title.*
import kotlinx.android.synthetic.main.layout_flow_tag.view.*
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.toast

/**
 * @author吕志豪 .
 * @date 18-3-8  下午4:23.
 * Github :https://github.com/lvzhihao100
 * E-Mail：1030753080@qq.com
 * 简书 :http://www.jianshu.com/u/6e525b929aac
 */

class LectureInfoActivity : BaseActivity() {

    private var id: Int = 0
    private var slimAdapterExVideo: SlimAdapterEx<LearnVideoListBean>? = null
    private var isMore: Boolean = false
    private var nextPage: Int = 0
    private val list = arrayListOf<LearnVideoListBean>()
    private var lectureInfo: LectureInfoActivity.LectureInfo? = null

    override fun initBinding() {
        setContentView(R.layout.activity_lecture_info)
        id = intent.getIntExtra(Config.ID, 0)
        initTopTitleBar(View.VISIBLE, "课程详情")
        iv_right.setImageResource(R.mipmap.addg)
        iv_right.visibility = View.VISIBLE
        popMenu(arrayListOf("匹配的需求", "收藏"), iv_right) { dialog, pos ->
            when (pos) {
                0 -> {
                    startActivity<TrainCourseMatchActivity>(Config.ID to id)
                }
                1 -> {
                    OkGo.post<HttpResult<*>>(HttpConfig.BASE_URL + HttpConfig.MAKER_COLLECT_ADD)
                            .params("userCompanyId", user.companyId)
                            .params("userGuid", user.guid)
                            .params("objectId", id) //被收藏的id（（企业/创客）产品id）
                            .params("objectType", 2) //0:收藏企业，1：企业产品 ，2：创客产品，3：其他创客
                            .params("objectGuid", "") //如果收藏的是创客，创客guid
                            .params("objectCompanyId", 0) //被收藏企业id
                            .execute(object : DialogCallBack<HttpResult<*>>(this) {
                                override fun onSuccess(response: Response<HttpResult<*>>?) {
                                    val result = response?.body()
                                    if (result?.status == 200) {
                                        toast("收藏成功")
                                    } else {
                                        toast(result?.msg ?: "收藏失败")
                                    }
                                }
                            })
                }
            }


        }


    }

    override fun initData() {


    }


    override fun setView() {
        val type = intent.getIntExtra(Config.TYPE, 0)
        OkGo.post<HttpResult<LectureInfo>>(HttpConfig.BASE_URL + HttpConfig.LEARN_LECTURE_INFO)
                .params("courseId", id)
                .execute(object : DialogCallBack<HttpResult<LectureInfo>>(this@LectureInfoActivity) {
                    override fun onSuccess(response: Response<HttpResult<LectureInfo>>) {
                        val httpResult = response.body()
                        if (httpResult.status == 200) {
                            lectureInfo = httpResult.items
                            updateView(httpResult.items)
                            if (type == 1) {
                                visitor("课程信息", "访问了${lectureInfo?.courseTheme}", "VISITOR_MAKER_PRODUCT_${lectureInfo?.userGuid}_${lectureInfo?.id}")
                            }
                        }
                    }
                })
    }

    private fun updateView(items: LectureInfo) {
        tv_title1.text = items.courseTheme
        val split = items.courseType?.split(",".toRegex())?.dropLastWhile { it.isEmpty() }?.toTypedArray()
        val autoFlowLayout = findViewById<AutoFlowLayout<String>>(R.id.autoFlowLayout)
        autoFlowLayout?.setAdapter(object : FlowAdapter<String>(split) {
            override fun getView(p0: Int): View {
                val view = LayoutInflater.from(this@LectureInfoActivity).inflate(R.layout.layout_flow_tag, null, false)
                view.tv_tag.text = split?.get(p0)
                return view
            }
        })
        tv_author.text = items.lectureName
        tv_time.text = items.createTime
        tv_object.visibility = if (items.courseStringer.isNullOrBlank()) View.GONE else View.VISIBLE
        tv_object.text = "授课对象:" + items.courseStringer
        tv_target.text = "课程目标:" + items.courseTarget
        tv_bg.text = "课程背景:" + items.courseBackground
        tv_price.text = "参考价格:" + items.coursePrice + "/天"
        tv_lecture_time.text = "课程时长:" + items.courseTimes
        tv_content.text = Html.fromHtml(items.courseOutlint)
        recyclerViewPic.layoutManager = GridLayoutManager(this, 3)
        recyclerViewPic.addItemDecoration(GridSpacingItemDecoration(3, 15, true))
        val slimAdapterEx = SlimAdapterEx.create()
                .register<String>(R.layout.grid_item_photo, SlimInjector<String> { data, injector ->
                    injector?.image(R.id.grid_img, data)
                })
                .attachTo(recyclerViewPic)
                .updateData(items.courseImage) as SlimAdapterEx<String>?
        ItemClickSupport.addTo(recyclerViewPic).setOnItemClickListener { recyclerView, position, v ->
            val imageList = arrayListOf<String>()
            slimAdapterEx?.data?.forEachIndexed { index, photoBean ->
                photoBean?.let { imageList.add(it) }
            }
            imgPathPreview(imageList, position)
        }


        recyclerViewVideo.layoutManager = LinearLayoutManager(this)
        slimAdapterExVideo = SlimAdapterEx.create().register<LearnVideoListBean>(R.layout.list_item_112, SlimInjector<LearnVideoListBean> { data, injector ->
            injector?.image(R.id.iv_poster, data?.videoImage)
                    ?.text(R.id.tv_title, data?.videoTitle)
                    ?.text(R.id.tv_time, data?.videoTime)
                    ?.with<TextView>(R.id.tv_types) { view ->
                        val textView = view as TextView
                        textView.text = ""
                        val split = data?.label?.split(",".toRegex())?.dropLastWhile { it.isEmpty() }?.toTypedArray()
                        split?.let {
                            for (s in it) {
                                val spanString = SpannableString(s)
                                val tagSpan = TagSpan(Color.GREEN, 10, 10)
                                tagSpan.setTextClick { text ->
                                    val bundle = Bundle()
                                    bundle.putInt(Config.POS, 2)
                                    bundle.putString(Config.FIELD, text.toString())
                                    startActivity(LearnSearchActivity::class.java, bundle)
                                }
                                spanString.setSpan(tagSpan, 0, s.length, Spannable.SPAN_INCLUSIVE_EXCLUSIVE)
                                textView.append(spanString)
                            }
                            textView.movementMethod = ClickMovementMethod.getInstance()
                        }

                    }
        }).attachTo(recyclerViewVideo).updateData(list as List<LearnVideoListBean>?) as SlimAdapterEx<LearnVideoListBean>?
        ItemClickSupport.addTo(recyclerViewVideo)
                .setOnItemClickListener { recyclerView, position, v ->
                    /* Bundle bundle = new Bundle();
                    bundle.putString(Config.URL, slimAdapterExVideo.getDataItem(position).getVideoUrl());
                    bundle.putString(Config.CONTENT, slimAdapterExVideo.getDataItem(position).getDescribe());
                    startActivity(YoukuPlayActivity.class, bundle);*/
                }
        ScrollLoadMoreUtil.loadMore(nestedScrollView) {
            if (isMore) {
                loadVideoData(nextPage)

            }
        }
        loadVideoData(0)
    }

    private fun loadVideoData(page: Int) {
        OkGo.post<HttpResultRows<LearnVideoListBean>>(HttpConfig.BASE_URL + HttpConfig.LEARN_LECTURE_VIDEO)
                .params("page", page)
                .params("courseId", id)
                .execute(object : DialogCallBack<HttpResultRows<LearnVideoListBean>>(this@LectureInfoActivity) {
                    override fun onSuccess(response: Response<HttpResultRows<LearnVideoListBean>>) {
                        val httpResult = response.body()
                        if (httpResult.status == 200) {
                            if (page == 0) {
                                slimAdapterExVideo?.updateData(httpResult.items.rows)
                            } else {
                                val startPos = slimAdapterExVideo?.data?.size
                                slimAdapterExVideo?.data?.addAll(httpResult.items.rows)
                                startPos?.let { slimAdapterExVideo?.notifyItemRangeInserted(it, httpResult.items.rows.size) }
                            }
                            if (httpResult.items.rows.size == 0) {

                                tv_status.text = "没有数据了"
                                isMore = false
                            } else {
                                tv_status.text = "加载数据中..."
                                nextPage = httpResult.items.page
                                isMore = true
                            }
                        }
                    }
                })
    }


    private fun visitor(mudular: String, option: String, key: String) {
        val time = PreferenceUtil.find(this, key, String::class.java)
        if (time == null || time.toLong() < System.currentTimeMillis() - 30 * 60 * 1000) {
            OkGo.post<HttpResult<*>>(HttpConfig.BASE_URL + HttpConfig.VISITOR_ADD)
                    .params("userGuid", user.guid)
                    .params("userCompanyId", user.companyId)
                    .params("makerGuid", lectureInfo?.userGuid)
                    .params("mudular", mudular)
                    .params("option", option)
                    .execute(object : JsonCallBack<HttpResult<*>>() {
                        override fun onSuccess(response: Response<HttpResult<*>>?) {
                            val result = response?.body()
                            if (result?.status == 200) {
                                PreferenceUtil.save(this@LectureInfoActivity, System.currentTimeMillis().toString(), key)
                                print(mudular)
                            }
                        }
                    })
        }
    }

    inner class LectureInfo {

        /**
         * courseImage : ["https://www.eqid.top:8009/LectureImage/20180109/2018010917064400831.jpg","https://www.eqid.top:8009/LectureImage/20180109/2018010917064411761.jpg","https://www.eqid.top:8009/LectureImage/20180109/2018010917064432239.jpg","https://www.eqid.top:8009/LectureImage/20180109/2018010917064442410.png","https://www.eqid.top:8009/LectureImage/20180109/2018010917064452644.png","https://www.eqid.top:8009/LectureImage/20180109/2018010917064462934.jpg","https://www.eqid.top:8009/LectureImage/20180109/2018010917064473244.png","https://www.eqid.top:8009/LectureImage/20180109/2018010917064483494.png","https://www.eqid.top:8009/LectureImage/20180109/2018010917064494313.png"]
         * Id : 6
         * courseType : 类型
         * courseTheme : 主题
         * courseTimes : 课程时长
         * courseOutlint : 课程大纲
         * courseStringer : 授课对象
         * userGuid : 1221b0fed5ec43d88e6b0d5a08e50e79
         * createTime : 2018-01-09T17:06:44
         * lectureName : 讲师名字
         * updater : null
         * updateTime : null
         * isdel : null
         * status : 0
         * courseMethod : 授课方法
         * coursePrice : 10000
         * courseBackground : 课程背景
         * courseTarget : 课程目标
         * courseImages : /LectureImage/20180109/2018010917064400831.jpg;/LectureImage/20180109/2018010917064411761.jpg;/LectureImage/20180109/2018010917064432239.jpg;/LectureImage/20180109/2018010917064442410.png;/LectureImage/20180109/2018010917064452644.png;/LectureImage/20180109/2018010917064462934.jpg;/LectureImage/20180109/2018010917064473244.png;/LectureImage/20180109/2018010917064483494.png;/LectureImage/20180109/2018010917064494313.png
         * commentCount : 0
         * coursewares : https://www.eqid.top:8009/LectureCourse/20180109/2018010917064400430.png
         * courseWareName : daminghu.png
         */

        var id: Int = 0
        var courseType: String? = null
        var courseTheme: String? = null
        var courseTimes: String? = null
        var courseOutlint: String? = null
        var courseStringer: String? = null
        var userGuid: String? = null
        var createTime: String? = null
            get() = DateUtil.format(field)
        var lectureName: String? = null
        var updater: String? = null
        var updateTime: String? = null
        var isdel: String? = null
        var status: Int = 0
        var courseMethod: String? = null
        var coursePrice: Int = 0
        var courseBackground: String? = null
        var courseTarget: String? = null
        var courseImages: String? = null
        var commentCount: Int = 0
        var coursewares: String? = null
        var courseWareName: String? = null
        var courseImage: List<String>? = null
    }
}
